package com.example.workassignback.Interceptor;

import com.example.workassignback.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @Auther: Lai Wenhao
 * @Date: 2024/5/30 15:15
 **/
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenUtil tokenUtil;


    private Long refreshTime = (long) 86400000;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            System.out.println("Method:OPTIONS");
            return true;
        }

        // 从请求头中获取Token
        String token = request.getHeader("Authorization");
        String userId;
        String userRole;

        // 解析Token，获取用户ID（假设Token中包含用户ID的解析逻辑）
        try {
            Map<String, ?> map = tokenUtil.parseToken(token);

            userId = (String) map.get("userId");
            userRole = (String) map.get("userRole");

//            System.out.println("userId = " + userId);
//            System.out.println("userRole = " + userRole);

            //判定时间
            long timeOfUse = System.currentTimeMillis() - Long.parseLong((String) map.get("timeStamp"));
            if (timeOfUse >= refreshTime) {
                System.out.println("token非法");
                return false;
            }

            //判定权限
            String path = request.getRequestURI();//获取请求路径
            String[] pathSegments = path.split("/");//获取第一级
            if (pathSegments.length > 1) {
                String firstSegment = pathSegments[1];
//                System.out.println("firstSegment = " + firstSegment);
                if ("doctor".equals(firstSegment) && !userRole.equals("Doctor")) {
                    System.out.println("权限不足");
                    return false;
                }
            }
        } catch (Exception e) {
            return false;
        }

        // 将用户ID存储到请求属性中
        request.setAttribute("currentUserId", userId);

        return true;
    }

}
